const { ipcMain } = require('electron');
const FundsAnalysisService = require('../services/FundsAnalysisService');
const { getCaseDatabaseInfo } = require('../database/knex');

const AnalysisReportService = require('../services/AnalysisReportService');

// Register analysis IPC handlers
function registerAnalysisHandlers() {
    // Funds Trace
    ipcMain.handle('analysis:funds-trace', async (event, { caseId, account, options }) => {
        try {
            console.log(`[IPC] analysis:funds-trace called for case ${caseId}, account ${account}`);
            const { dbPath } = await getCaseDatabaseInfo(caseId);
            return await FundsAnalysisService.traceFunds(caseId, dbPath, account, options);
        } catch (error) {
            console.error('Failed to trace funds:', error);
            throw error;
        }
    });

    // Report Management
    ipcMain.handle('analysis:save-report', async (event, { caseId, subjectId, reportData }) => {
        return await AnalysisReportService.saveReport(caseId, subjectId, reportData);
    });

    ipcMain.handle('analysis:load-report', async (event, { caseId, subjectId }) => {
        return await AnalysisReportService.loadReport(caseId, subjectId);
    });

    ipcMain.handle('analysis:delete-report', async (event, { caseId, subjectId }) => {
        return await AnalysisReportService.deleteReport(caseId, subjectId);
    });

    // Plugins
    ipcMain.handle('analysis:list-plugins', async () => {
        const PluginManager = require('../services/PluginManager');
        return PluginManager.getAll();
    });

    ipcMain.handle('analysis:run-plugin', async (event, { pluginId, caseId, params }) => {
        const PluginManager = require('../services/PluginManager');
        const { dbPath } = await getCaseDatabaseInfo(caseId);

        // Build context
        const context = {
            caseId,
            dbPath,
            // Add other context services if needed, e.g. SubjectService?
            // Plugins usually just need DB access.
        };

        return await PluginManager.execute(pluginId, params, context);
    });

    ipcMain.handle('analysis:import-plugin', async (event, sourcePath) => {
        const PluginManager = require('../services/PluginManager');
        return await PluginManager.importPlugin(sourcePath);
    });
}

module.exports = registerAnalysisHandlers;
